package com.yaorange.teaching.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yaorange.common.core.exception.ServiceException;
import com.yaorange.common.core.utils.DateUtils;
import com.yaorange.common.security.utils.SecurityUtils;
import com.yaorange.teaching.bo.ExamRecordBo;
import com.yaorange.teaching.bo.ScoreDistributionBo;
import com.yaorange.teaching.bo.ScoreTrendBo;
import com.yaorange.teaching.domain.YaClass;
import com.yaorange.teaching.domain.YaExamDetail;
import com.yaorange.teaching.domain.YaStudent;
import com.yaorange.teaching.mapper.YaClassMapper;
import com.yaorange.teaching.mapper.YaStudentMapper;
import com.yaorange.teaching.service.IYaExamDetailService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yaorange.teaching.mapper.YaExamRecordMapper;
import com.yaorange.teaching.domain.YaExamRecord;
import com.yaorange.teaching.service.IYaExamRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生成绩记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-13
 */
@Service
public class YaExamRecordServiceImpl implements IYaExamRecordService
{
    @Autowired
    private YaExamRecordMapper yaExamRecordMapper;

    @Autowired
    private IYaExamDetailService yaExamDetailService;

    @Autowired
    private YaClassMapper yaClassMapper;


    @Autowired
    private YaStudentMapper yaStudentMapper;

    /**
     * 查询学生成绩记录
     *
     * @param id 学生成绩记录主键
     * @return 学生成绩记录
     */
    @Override
    public YaExamRecord selectYaExamRecordById(Long id)
    {
        return yaExamRecordMapper.selectYaExamRecordById(id);
    }

    /**
     * 查询学生成绩记录列表
     *
     * @param yaExamRecord 学生成绩记录
     * @return 学生成绩记录
     */
    @Override
    public List<YaExamRecord> selectYaExamRecordList(YaExamRecord yaExamRecord)
    {
        return yaExamRecordMapper.selectYaExamRecordList(yaExamRecord);
    }

    /**
     * 新增学生成绩记录
     *
     * @param yaExamRecord 学生成绩记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertYaExamRecord(ExamRecordBo yaExamRecord)
    {
        List<YaExamDetail> examDetails = yaExamRecord.getExamDetails();
        //1.新增测试记录（1方）
        //维护冗余字段
            //平均分
        yaExamRecord.setAvgComputerScore(computeAvgComputerScore(examDetails));
        yaExamRecord.setAvgWrittenScore(computeAvgWrittenScore(examDetails));
            //班级名字
        YaClass yaClass = yaClassMapper.selectYaClassById(yaExamRecord.getClassesId());
        if (ObjectUtils.isEmpty(yaClass)) {
            throw new ServiceException("班级不存在");
        }
        yaExamRecord.setClassesName(yaClass.getClassName());
        yaExamRecord.setCreateBy(SecurityUtils.getUsername());
        yaExamRecord.setCreateTime(DateUtils.getNowDate());
        yaExamRecordMapper.insertYaExamRecord(yaExamRecord);
        //2.新增测试记录详情(多方,需要维护外键)
        examDetails.forEach(e->e.setExamRecordId(yaExamRecord.getId()));
        yaExamDetailService.saveBatch(examDetails,10);
        return 1;
    }

    private Long computeAvgComputerScore(List<YaExamDetail> examDetails) {
        //将YaExamDetail转成Long，再计算long的平均值
        return (long) examDetails.stream().filter(e->e.getComputerScore()!=null).mapToLong(YaExamDetail::getComputerScore).average().orElse(0L);
    }

    private Long computeAvgWrittenScore(List<YaExamDetail> examDetails) {
        //将YaExamDetail转成Long，再计算long的平均值
        return (long) examDetails.stream().filter(e-> ObjectUtils.isNotEmpty(e.getWrittenScore())).mapToLong(YaExamDetail::getWrittenScore).average().orElse(0L);
    }

    /**
     * 修改学生成绩记录
     *
     * @param yaExamRecord 学生成绩记录
     * @return 结果
     */
    @Override
    public int updateYaExamRecord(YaExamRecord yaExamRecord)
    {
        yaExamRecord.setUpdateTime(DateUtils.getNowDate());
        return yaExamRecordMapper.updateYaExamRecord(yaExamRecord);
    }

    /**
     * 批量删除学生成绩记录
     *
     * @param ids 需要删除的学生成绩记录主键
     * @return 结果
     */
    @Override
    public int deleteYaExamRecordByIds(Long[] ids)
    {
        return yaExamRecordMapper.deleteYaExamRecordByIds(ids);
    }

    /**
     * 删除学生成绩记录信息
     *
     * @param id 学生成绩记录主键
     * @return 结果
     */
    @Override
    public int deleteYaExamRecordById(Long id)
    {
        return yaExamRecordMapper.deleteYaExamRecordById(id);
    }

    @Override
    public List<YaExamDetail> selectYaExamDetailList(Long classesId) {
        return yaExamRecordMapper.selectYaExamDetailList(classesId);
    }

    @Override
    @Transactional(readOnly = true)
    public Integer queryLastWeek(Long classesId, Long stage) {
        return yaExamRecordMapper.selectLastWeek(classesId,stage);
    }

    @Override
    @Transactional(readOnly = true)
    public ScoreTrendBo queryScoreTrend() {
        Long studentId = SecurityUtils.getUserId();
        List<Map<String, Object>> list = yaExamRecordMapper.selectScoreTrend(studentId);
        //将list中的每个map对象的key装入stageWeekList,value装入stageWeekScoreList
        ScoreTrendBo result = new ScoreTrendBo();
        int size = list.size();
        List<String> stageWeekList = new ArrayList<>(size);
        List<Integer> stageWeekScoreList = new ArrayList<>(size);
        list.forEach(map->{
            String title = map.get("title").toString();
            int average_score = ((BigDecimal) map.get("average_score")).intValue();
            stageWeekList.add(title);
            stageWeekScoreList.add(average_score);
        });
        result.setStageWeekList(stageWeekList);
        result.setStageWeekScoreList(stageWeekScoreList);
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public ScoreDistributionBo queryScoreDistribution() {
        ScoreDistributionBo result = new ScoreDistributionBo();
        Long studentId = SecurityUtils.getUserId();
        YaStudent yaStudent = yaStudentMapper.selectYaStudentById(studentId);
        Long classesId = yaStudent.getClassesId();
        List<Map<String, Object>> list = yaExamRecordMapper.selectScoreDistribution(classesId);
        int size = list.size();
        List<String> scoreRangeList = new ArrayList<>(size);
        List<Long> cntList = new ArrayList<>(size);
        list.forEach(map->{
            String scoreRange = map.get("score_range").toString();
            Long value = (Long) map.get("cnt");
            scoreRangeList.add(scoreRange);
            cntList.add(value);
        });
        result.setScoreRangeList(scoreRangeList);
        result.setCntList(cntList);
        return result;
    }
}
